package com.example.login.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FileController {
    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename(); // 获取文件名
        String filePath = "D:/temp/"; // 设置文件保存路径
        File dest = new File(filePath + fileName); // 创建目标文件对象
        try {
            file.transferTo(dest); // 将上传的文件保存到目标文件中
            return ResponseEntity.ok("w文件上传成功!");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
        }
    }
    @PostMapping("/uploadMultiple")
    public ResponseEntity<String> handleMultipleFileUpload(@RequestParam("files") List<MultipartFile> files) {
        String filePath = "D:/temp/"; // 设置文件保存路径
        List<String> uploadedFiles = new ArrayList<>();

        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename(); // 获取文件名
            File dest = new File(filePath + fileName); // 创建目标文件对象
            try {
                file.transferTo(dest); // 将上传的文件保存到目标文件中
                uploadedFiles.add(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败!");
            }
        }

        return ResponseEntity.ok("文件上传成功: " + String.join(", ", uploadedFiles));
    }
}

